package com.ruoyi.manage.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.manage.domain.CrApplication;
import com.ruoyi.manage.service.ICrApplicationService;

/**
 * 学生申请Controller
 * 
 * @author ruoyi
 * @date 2024-09-24
 */
@RestController
@RequestMapping("/campus/application")
public class CrApplicationController extends BaseController
{
    @Autowired
    private ICrApplicationService crApplicationService;

    /**
     * 查询学生申请列表
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrApplication crApplication)
    {
        startPage();
        List<CrApplication> list = crApplicationService.selectCrApplicationList(crApplication);
        return getDataTable(list);
    }

    /**
     * 导出学生申请列表
     */
    @PreAuthorize("@ss.hasPermi('manage:application:export')")
    @Log(title = "学生申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrApplication crApplication)
    {
        List<CrApplication> list = crApplicationService.exportApplications(crApplication);
        ExcelUtil<CrApplication> util = new ExcelUtil<CrApplication>(CrApplication.class);
        util.exportExcel(response, list, "学生申请数据");
    }

    /**
     * 获取学生申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:application:query')")
    @GetMapping(value = "/{applicationId}")
    public AjaxResult getInfo(@PathVariable("applicationId") Long applicationId)
    {
        return success(crApplicationService.selectCrApplicationByApplicationId(applicationId));
    }

    /**
     * 新增学生申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:add')")
    @Log(title = "学生申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrApplication crApplication)
    {
        return toAjax(crApplicationService.insertCrApplication(crApplication));
    }

    /**
     * 修改学生申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:edit')")
    @Log(title = "学生申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrApplication crApplication)
    {
        return toAjax(crApplicationService.updateCrApplication(crApplication));
    }

    /**
     * 删除学生申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:remove')")
    @Log(title = "学生申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{applicationIds}")
    public AjaxResult remove(@PathVariable Long[] applicationIds)
    {
        return toAjax(crApplicationService.deleteCrApplicationByApplicationIds(applicationIds));
    }

    // ========== 业务相关接口 ==========

    /**
     * 学生提交申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:submit') or @ss.hasPermi('campus:student:application:submit') or @ss.hasRole('student')")
    @Log(title = "提交申请", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submitApplication(@RequestBody Map<String, Object> params)
    {
        Long studentId = Long.valueOf(params.get("studentId").toString());
        Long recruitmentId = Long.valueOf(params.get("recruitmentId").toString());
        String applicationContent = params.get("applicationContent").toString();
        
        return toAjax(crApplicationService.submitApplication(studentId, recruitmentId, applicationContent));
    }

    /**
     * 社团审核申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:review') or @ss.hasRole('club')")
    @Log(title = "审核申请", businessType = BusinessType.UPDATE)
    @PutMapping("/review")
    public AjaxResult reviewApplication(@RequestBody Map<String, Object> params)
    {
        Long applicationId = Long.valueOf(params.get("applicationId").toString());
        String status = params.get("status").toString();
        String reviewComment = (String) params.get("reviewComment");
        Integer reviewScore = params.get("reviewScore") != null ? 
            Integer.valueOf(params.get("reviewScore").toString()) : null;
        
        return toAjax(crApplicationService.reviewApplication(applicationId, status, reviewComment, reviewScore));
    }

    /**
     * 批量审核申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:review') or @ss.hasRole('club')")
    @Log(title = "批量审核申请", businessType = BusinessType.UPDATE)
    @PutMapping("/batchReview")
    public AjaxResult batchReviewApplications(@RequestBody Map<String, Object> params)
    {
        Long[] applicationIds = ((List<Long>) params.get("applicationIds")).toArray(new Long[0]);
        String status = params.get("status").toString();
        String reviewComment = (String) params.get("reviewComment");
        
        int successCount = crApplicationService.batchReviewApplications(applicationIds, status, reviewComment);
        return success("成功审核 " + successCount + " 条申请");
    }

    /**
     * 撤回申请
     */
    @PreAuthorize("@ss.hasPermi('manage:application:withdraw') or @ss.hasRole('student')")
    @Log(title = "撤回申请", businessType = BusinessType.UPDATE)
    @PutMapping("/withdraw/{applicationId}")
    public AjaxResult withdrawApplication(@PathVariable Long applicationId)
    {
        Long studentId = getUserId(); // 从当前登录用户获取
        return toAjax(crApplicationService.withdrawApplication(applicationId, studentId));
    }

    /**
     * 根据学生ID查询申请列表
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list') or @ss.hasRole('student')")
    @GetMapping("/student/{studentId}")
    public AjaxResult getApplicationsByStudent(@PathVariable Long studentId)
    {
        List<CrApplication> applications = crApplicationService.selectApplicationsByStudentId(studentId);
        return success(applications);
    }

    /**
     * 根据社团ID查询申请列表
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list') or @ss.hasRole('club')")
    @GetMapping("/club/{clubId}")
    public AjaxResult getApplicationsByClub(@PathVariable Long clubId)
    {
        List<CrApplication> applications = crApplicationService.selectApplicationsByClubId(clubId);
        return success(applications);
    }

    /**
     * 根据招聘ID查询申请列表
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list')")
    @GetMapping("/recruitment/{recruitmentId}")
    public AjaxResult getApplicationsByRecruitment(@PathVariable Long recruitmentId)
    {
        List<CrApplication> applications = crApplicationService.selectApplicationsByRecruitmentId(recruitmentId);
        return success(applications);
    }

    /**
     * 获取申请统计信息
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list')")
    @GetMapping("/statistics/recruitment/{recruitmentId}")
    public AjaxResult getApplicationStatistics(@PathVariable Long recruitmentId)
    {
        Map<String, Object> statistics = crApplicationService.getApplicationStatistics(recruitmentId);
        return success(statistics);
    }

    /**
     * 获取学生申请统计
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list')")
    @GetMapping("/statistics/student/{studentId}")
    public AjaxResult getStudentApplicationStatistics(@PathVariable Long studentId)
    {
        Map<String, Object> statistics = crApplicationService.getStudentApplicationStatistics(studentId);
        return success(statistics);
    }

    /**
     * 获取社团申请统计
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list')")
    @GetMapping("/statistics/club/{clubId}")
    public AjaxResult getClubApplicationStatistics(@PathVariable Long clubId)
    {
        Map<String, Object> statistics = crApplicationService.getClubApplicationStatistics(clubId);
        return success(statistics);
    }

    /**
     * 检查是否重复申请
     */
    @GetMapping("/checkDuplicate")
    public AjaxResult checkDuplicateApplication(Long studentId, Long recruitmentId)
    {
        boolean isDuplicate = crApplicationService.checkDuplicateApplication(studentId, recruitmentId);
        return success(isDuplicate);
    }

    /**
     * 获取待审核申请数量
     */
    @PreAuthorize("@ss.hasPermi('manage:application:list')")
    @GetMapping("/pendingCount/{clubId}")
    public AjaxResult getPendingApplicationCount(@PathVariable Long clubId)
    {
        long count = crApplicationService.getPendingApplicationCount(clubId);
        return success(count);
    }
}